/*
 * @Descripttion: GGB
 * @version: 1.0
 * @Author: GGB
 * @Date: 2021-07-30 15:34:26
 * @LastEditors: GGB
 * @LastEditTime: 2021-07-30 17:29:20
 */
import 'package:flutter/material.dart';
import 'package:flutter_faster_study/apps/QR/screens/components/button_widget.dart';
import 'package:flutter_faster_study/apps/save_preferences/utils/user_simple_preferences.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key key}) : super(key: key);

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen>
    with SingleTickerProviderStateMixin {
  final formKey = GlobalKey<FormState>();
  String name = '';
  DateTime birthday;
  List<String> pets = [];
  List<bool> selected = [false, false, false, false];

  @override
  void initState() {
    super.initState();
    name = UserSimplePreferences.getUsername() ?? '';
    birthday = UserSimplePreferences.getBirthday();
    pets = UserSimplePreferences.getPets() ?? [];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: ListView(
          padding: EdgeInsets.all(16),
          children: [
            Text(
              "保存个人偏好",
              style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 30,
                color: Colors.white,
              ),
            ),
            const SizedBox(height: 32),
            buildName(),
            const SizedBox(height: 12),
            buildBirthday(),
            const SizedBox(height: 12),
            buildPets(),
            const SizedBox(height: 12),
            buildButton(),
          ],
        ),
      ),
    );
  }

  buildName() => buildTitle(
        title: "用户名",
        child: TextFormField(
          initialValue: name,
          decoration:
              InputDecoration(border: OutlineInputBorder(), hintText: "请输入用户名"),
          onChanged: (value) => setState(() {
            name = value;
          }),
        ),
      );

  buildTitle({String title, Widget child}) => Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            title,
            style: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 18,
            ),
          ),
          SizedBox(height: 8),
          child,
        ],
      );

  buildButton() => ButtonWidget(
      text: "保存",
      onClicked: () async {
        print(name);
        await UserSimplePreferences.setUsername(name);
        await UserSimplePreferences.setPets(pets);
        await UserSimplePreferences.setBirthday(birthday);
      });

  buildBirthday() => buildTitle(
        title: "生日",
        child: InkWell(
          onTap: () async {
            var result = await showDatePicker(
                context: context,
                initialDate: DateTime.now(),
                firstDate: DateTime(2020),
                lastDate: DateTime(2030));
            print('$result');
            setState(() {
              birthday = result;
            });
            print(birthday);
          },
          child: Container(
            padding: EdgeInsets.all(20),
            decoration: BoxDecoration(
              border: Border.all(color: Colors.green),
            ),
            child: Row(
              children: [
                Icon(Icons.date_range),
                SizedBox(width: 20),
                Text(birthday == null ? '未设置' : birthday.toString()),
              ],
            ),
          ),
        ),
      );

  buildPets() {
    final List<String> petsList = ['猫', '狗', '牛', '马'];
    List.generate(petsList.length, (index) {
      setState(() {
        selected[index] = pets.contains(petsList[index]);
      });
    });
    return buildTitle(
        title: "宠物",
        child: ToggleButtons(
          isSelected: selected,
          children:
              List.generate(petsList.length, (index) => Text(petsList[index]))
                  .toList(),
          onPressed: (index) {
            String pet = petsList[index];
            setState(() {
              selected[index] = !selected[index];
              pets.contains(petsList[index]) ? pets.remove(pet) : pets.add(pet);
            });
          },
        ));
  }
}
